<template>
  <div class="divide-page">
    <div @click="page--">上一页</div>
    <p v-show="showPage[0] > 1">...</p>
    <div v-for="i in showPage"
         :class="{active: i === page}"
         @click="page = i">
      {{ i }}
    </div>
    <p v-show="showPage[showPage.length - 1] < total">...</p>
    <div @click="page++">下一页</div>
  </div>
</template>

<script lang="ts"
        setup>
import {computed} from 'vue'

let props = withDefaults(defineProps<{
  modelValue: number,
  total: number,
  // 必须是奇数
  showPageCount?: number
}>(), {
  showPageCount: 5
})

let emits = defineEmits<{
  (e: 'update:modelValue', v: number): void
}>()

let page = computed({
  get(): number {
    return props.modelValue
  },
  set(v: number): void {
    if (v < 1)
      v = 1
    if (v > props.total)
      v = props.total
    emits('update:modelValue', v)
  }
})
// 显示可切换的页码
let showPage = computed((): number[] => {
  let half = Math.floor(props.showPageCount / 2)
  let start: number = Math.max(page.value - half, 1)
  let end: number = Math.min(page.value + half, props.total)
  if (page.value <= half)
    end = Math.min(props.total, props.showPageCount)
  if (page.value >= props.total - half)
    start = Math.max(props.total - props.showPageCount + 1, 1)

  let list: number[] = []
  for (let i: number = start; i <= end; i++)
    list.push(i)
  return list
})
</script>

<style lang="less"
       scoped>
.divide-page {
  padding: 30px;
  display: flex;
  justify-content: center;

  div {
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    cursor: pointer;

    &.active {
      color: white;
      background-color: @xtxColor;
    }
  }

  * ~ * {
    margin-left: 10px;
  }
}
</style>